package com.dongdong.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSONObject;
import com.dongdong.data.Result;
import com.dongdong.em.ResultEmnu;
import com.dongdong.pojo.TbAddress;
import com.dongdong.pojo.TbOrder;
import com.dongdong.pojo.TbOrderItem;
import com.dongdong.pojo.TbUser;
import com.dongdong.service.CartService;
import com.dongdong.service.OrderService;
import com.dongdong.util.CookieUtils;
import com.dongdong.util.IdWorker;
import com.dongdong.vo.Cart;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("cart")
public class CartController {
    @Reference(timeout = 5000)
    private CartService cartService;
    @Autowired
    private RedisTemplate redisTemplate;
    @Reference(timeout = 5000)
    private OrderService orderService;
    @RequestMapping("toCart")
    public String toCart(){
        return "/cart";
    }
    @RequestMapping("addCart")
    public String addCart(HttpServletRequest request, HttpServletResponse response, Long itemId, Integer num){
        //==============未登录============
        //1,从cookie中查询数据
        List<Cart> cartList = getCart(request,response);
        //2,保存购物车
        cartList = cartService.addCart(cartList,itemId,num);
        TbUser user = (TbUser) SecurityUtils.getSubject().getPrincipal();
        //3,从新放回在cookie中
        if (user == null){
            CookieUtils.setCookie(request,response,"cartList",JSONObject.toJSONString(cartList),true);
        }else {
            cartService.addCartToRedis(cartList, user.getUsername());
        }
        return "/success-cart";
    }
    @RequestMapping("adddCart")
    public String adddCart(HttpServletRequest request, HttpServletResponse response, Long itemId, Integer num){
        //==============未登录============
        //1,从cookie中查询数据
        List<Cart> cartList = getCart(request,response);
        //2,保存购物车
        cartList = cartService.addCart(cartList,itemId,num);
        TbUser user = (TbUser) SecurityUtils.getSubject().getPrincipal();
        //3,从新放回在cookie中
        if (user == null){
            CookieUtils.setCookie(request,response,"cartList",JSONObject.toJSONString(cartList),true);
        }else {
            cartService.addCartToRedis(cartList, user.getUsername());
        }
        return "/cart";
    }
    @RequestMapping("getCart")
    @ResponseBody
    public List<Cart> getCart(HttpServletRequest request,HttpServletResponse response){
        TbUser user = (TbUser) SecurityUtils.getSubject().getPrincipal();
        //从cookie中获取购物车数据
        String cartListStr = CookieUtils.getCookieValue(request, "cartList", true);
        //判断cookie值是否为空
        if (StringUtils.isBlank(cartListStr)){
            cartListStr = "[]";
        }
        List<Cart> cartListCookie = JSONObject.parseArray(cartListStr, Cart.class);
        if (user == null){
            return cartListCookie;
        }else{
            List<Cart> cartListRedis = cartService.findCartListRedis(user.getUsername());
            if (cartListCookie.size() > 0){

                //合并购物车
                List<Cart> cartListMerage = cartService.merageCart(cartListRedis, cartListCookie);
                //将合并的购物车合并到redis中
                cartService.addCartToRedis(cartListMerage, user.getUsername());
                //删除cookie
                CookieUtils.deleteCookie(request,response,"cartList");
                return cartListMerage;
            }
            return cartListRedis;
        }
    }
    @RequestMapping("getUser")
    @ResponseBody
    public Integer getUser(){
        TbUser user = (TbUser)SecurityUtils.getSubject().getPrincipal();
        if (user != null){
            return 1;
        }else {
            return 2;
        }
    }
    @RequestMapping("getOrderInfo")
    public String getOrderInfo(){
        return "getOrderInfo";
    }
    @RequestMapping("increaseInfo")
    @ResponseBody
    public Result increaseInfo(Long id){
        try {
            TbUser user = (TbUser) SecurityUtils.getSubject().getPrincipal();
            TbAddress tbAddress = orderService.getAddressById(id);
            List<Cart> cartList = (List<Cart>) redisTemplate.boundHashOps("cartList").get(user.getUsername());
            String title = null;
            IdWorker workerId = new IdWorker();
            long idOrder = workerId.nextId();//母订单号
            Map<String,Object> map = new HashMap<>();
            for (Cart cart : cartList) {
                IdWorker idWorker = new IdWorker();
                long orderId = idWorker.nextId();
                TbOrder tbOrder = new TbOrder();
                tbOrder.setOrderId(orderId);//子订单Id
                tbOrder.setUserId(tbAddress.getUserId());
                tbOrder.setPaymentType("1");
                tbOrder.setStatus("1");
                tbOrder.setCreateTime(new Date());
                tbOrder.setUpdateTime(new Date());
                tbOrder.setReceiverAreaName(tbAddress.getAddress());
                tbOrder.setReceiverMobile(tbAddress.getMobile());
                tbOrder.setReceiver(tbAddress.getContact());
                tbOrder.setSourceType("2");
                tbOrder.setSellerId(user.getUsername());
                tbOrder.setOutTradeNo(idOrder);//母订单号
                //循环购物车明细
                double menoy = 0;
                for (TbOrderItem orderItem : cart.getOrderItemList()) {
                    orderItem.setId(idWorker.nextId());
                    orderItem.setOrderId(orderId);//子订单号
                    orderItem.setSellerId(cart.getSellerId());
                    orderItem.setOutTradeNo(idOrder);//母订单
                    menoy += orderItem.getTotalFee().doubleValue();//支付金额的累加
                    orderService.insertOrderItem(orderItem);
                    title = orderItem.getTitle();
                }
                map.put("menoy",menoy);
                map.put("orderId",idOrder);
                map.put("title",title);
                tbOrder.setPayment(new BigDecimal(menoy));
                orderService.insertTbOrder(tbOrder);
            }
            redisTemplate.boundHashOps("cartList").delete(user.getUsername());
            return Result.respone(ResultEmnu.SUCCESS).setData(map);
        }catch (Exception e){
            e.printStackTrace();
            return Result.respone(ResultEmnu.ERROR);
        }
    }
}
